package user

import (
	"dy/pkg/code"
	"dy/pkg/jwt"
	"dy/pkg/util"

	"github.com/gin-gonic/gin"
)

func (u *ControllerUser) Login(ctx *gin.Context) {
	type param struct {
		UserName string `form:"username" json:"username" binding:"required"`
		Password string `form:"password" json:"password" binding:"required"`
	}
	var request param
	err := ctx.Bind(&request)
	if err != nil {
		code.ErrReturn(ctx, err.Error())
		return
	}
	search := map[string]interface{}{}
	err = util.StructTo(&request, &search)
	userId, flag, err := u.srv.User().Login(ctx, search)
	if flag == false {
		code.ErrReturn(ctx, "fail, please check the username and password")
		return
	}
	if err != nil {
		code.ErrReturn(ctx, err.Error())
		return
	}

	token, err := jwt.GetToken(userId)
	if err != nil {
		code.ErrReturn(ctx, err.Error())
		return
	}

	ctx.JSON(200, gin.H{
		"status_code": 0,
		"status_msg":  "success",
		"user_id":     userId,
		"token":       token,
	})
	return
}
